import json
import logging
import os
import traceback
from datetime import datetime

from django.db import transaction
from django.db.models import Sum
from django.forms import model_to_dict
from django.http import JsonResponse
from rest_framework import status
from Model.models import Contract, District, Subdistrict, Community, Address, IncomeDetail, IncomeTotal, Package, \
    FlowDiagram
from Model.modelsView import ContractInfo
from radius.models import Radacct
from tools.createBusiness import createAuthInfo, getOnlineState, createIncomeTotal, createIncomeDetail, \
    createRenewContract, deleteAuth, createRefund, updataIncome
from tools.Tools import addTime, createHandleLog, getCurrentUser

logger_info = logging.getLogger('info')
res = dict()


# 密码变更
@transaction.atomic
def ModifyPassword(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            contract_id = body.get('contract_id')
            account_number = body.get('account_number')
            account_password = body.get('account_password')
            service_package = body.get('service_package')
            end_date = body.get('end_date')
            createAuthInfo(account_number, account_password, service_package, end_date)
            Contract.objects.filter(account_number=account_number).update(account_password=account_password)
            createHandleLog('密码变更', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《密码变更》权限 新增内容 {body}')
            res['status'] = 200
            res['message'] = '密码修改成功！'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 账号生效
@transaction.atomic
def AccountEffective(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            contract_id = body.get('contract_id')
            account_number = body.get('account_number')
            account_password = body.get('account_password')
            service_package = body.get('service_package')
            end_date = body.get('end_date')
            createAuthInfo(account_number, account_password, service_package, str(end_date)[:10])
            createHandleLog('账号生效', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《账号生效》权限 生效内容 {body}')
            res['status'] = 200
            res['message'] = '账号生效成功！'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 账号下线
@transaction.atomic
def AccountKick(request):
    try:
        res.clear()
        if request.method == "POST":
            body = json.loads(request.body)
            account_number = body.get('account_number')
            cli = Radacct.objects.filter(username=account_number)
            if cli.__len__() <= 0:
                res['status'] = 400
                res['message'] = '未拨号,不能踢下线.'
            else:
                if cli.last().acctstoptime is None:
                    os.system('echo "Acct-Session-Id=' + cli.last().acctsessionid + '" > packet.txt')
                    os.system('echo "User-Name=' + cli.last().username + '" >> packet.txt')
                    os.system('echo "Framed-IP-Address=' + cli.last().framedipaddress + '" >> packet.txt')
                    os.system(
                        'cat packet.txt | radclient -x ' + cli.last().nasipaddress + ':3799 disconnect testing123')
                    res['status'] = 200
                    res['message'] = '下线成功.'
                else:
                    res['status'] = 400
                    res['message'] = '当前离线,下线失败.'
            createHandleLog('账号下线', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《账号下线》权限 新增内容 {body}')
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['msg'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 地址迁移
@transaction.atomic
def Transfer(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            contract_id = body.get('contract_id')
            district = body.get('district')
            subdistrict = body.get('subdistrict')
            community = body.get('community')
            address = body.get('address')
            detail_address = body.get('detail_address')
            memo = body.get('memo')
            con = Contract.objects.get(contract_id=contract_id)
            con.district = district
            con.subdistrict = subdistrict
            con.community = community
            con.address = address
            con.detail_address = detail_address
            con.memo = memo
            district_name = District.objects.get(district_id=district).name
            subdistrict_name = Subdistrict.objects.get(subdistrict_id=subdistrict).name
            community_name = Community.objects.get(community_id=community).name
            address_name = Address.objects.get(address_id=address).name
            con.install_address = district_name + subdistrict_name + community_name + address_name + detail_address
            con.save()
            createHandleLog('地址迁移', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《地址迁移》权限 新增内容 {body}')
            res['status'] = 200
            res['message'] = '地址迁移成功！'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 赠送时长
@transaction.atomic
def GiftDuration(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            contract_id = body.get('contract_id')
            date = body.get('date')
            contract = Contract.objects.get(contract_id=contract_id)
            lastData = Contract.objects.filter(account_number=contract.account_number).last()
            detail = IncomeDetail.objects.filter(contract_id=lastData.contract_id).last()
            lastData.end_date = addTime(lastData.end_date, date)
            lastData.save()
            det = IncomeDetail.objects.create()
            det.detail_id = det.id
            det.contract_id = contract_id
            det.total_id = detail.total_id
            det.detail_type = 5
            det.amount = 0
            det.memo = f'赠送{date}天时长'
            det.refund_state = 0
            det.pay_time = datetime.now()
            det.save()
            createHandleLog('赠送时长', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《赠送时长》权限 新增内容 {body}')
            res['status'] = 200
            res['message'] = '赠送时长成功！'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def getContractDetail(request):
    """
    @param request
    获取账号登录情况及改客户所有合同
    """
    res.clear()
    try:
        if request.method == 'GET':
            contractId = request.GET.get('contractId')
            account_number = Contract.objects.get(contract_id=contractId).account_number
            state, info = getOnlineState(account_number)
            dataList = list(ContractInfo.objects.filter(account_number=account_number).values())
            incomeSource = list(IncomeDetail.objects.filter(contract_id=contractId).values())
            flow = model_to_dict(FlowDiagram.objects.get(account_number=account_number))
            data = {'state': state, 'info': info, 'source': dataList, 'income': incomeSource, "flow": flow}
            res['status'] = 200
            res['data'] = data
            res['message'] = '请求成功'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['messages'] = '请求错误'
        res['status'] = 400
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def getIncomeDetailByContractId(request):
    """
    获取收入详情根据合同ID
    """
    res.clear()
    try:
        if request.method == 'GET':
            contractId = request.GET.get('contractId')
            data = list(IncomeDetail.objects.filter(contract_id=contractId).values())
            res['status'] = 200
            res['data'] = data
            res['message'] = '请求成功'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def renewContract(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            contractId = body.get('contractId')
            memo = body.get('memo')
            service_package = body.get('service_package')
            oldData = Contract.objects.get(contract_id=contractId)
            package_price = Package.objects.get(package_id=service_package).package_price
            operator = getCurrentUser(request)
            # 续费数据
            renewData = createRenewContract(oldData, service_package, str(operator), memo)
            # 收入数据
            totalId = createIncomeTotal(renewData.contract_id, renewData.client_id, 2, str(operator), memo)
            createIncomeDetail(totalId, renewData.contract_id, 1, package_price, memo=memo)
            # 认证数据
            createAuthInfo(renewData.account_number, renewData.account_password, renewData.service_package,
                           str(renewData.end_date)[:10])
            total_sum = IncomeDetail.objects.filter(total_id=totalId).aggregate(sum=Sum('amount'))['sum']
            total = IncomeTotal.objects.get(total_id=totalId)
            total.amount = total_sum
            total.save()
            createHandleLog('用户续费', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《用户续费》权限  操作内容 {body}')
            res['status'] = 200
            res['message'] = '续费成功'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def refundContract(request):
    """
    用户退费
    """
    res.clear()
    try:
        if request.method == "POST":
            body = json.loads(request.body)
            refund_type = body.get('refund_type')
            expense_total = body.get('expense_total')
            is_active = body.get('is_active')
            expense_type = body.get('expense_type')
            contractId = body.get('contractId')
            expense_total = float(expense_total)
            contractData = Contract.objects.get(contract_id=contractId)
            detail_type = 1 if (expense_type == 0 or not expense_type) else 4
            if detail_type == 1 or expense_type == 0:
                product = None
            if detail_type == 4 and expense_type == 1:
                product = '光猫'
            if detail_type == 4 and expense_type == 2:
                product = '路由器'
            detailData = IncomeDetail.objects.get(contract_id=contractId, detail_type=detail_type,
                                                  equipment_type=product)
            # 判断退费金额是否小于当前收入金额
            if detailData.amount < expense_total:
                res['status'] = 400
                res['message'] = '退费金额不可小于当前收入金额'
                return JsonResponse(res, status=status.HTTP_200_OK)
            if refund_type == 1:
                #  全部退费
                #  删除认证
                deleteAuth(contractData.account_number)
                #  收入金额为0
                updataIncome(contractId)
                #  合同状态 终止
                Contract.objects.filter(account_number=contractData.account_number).update(state=3)
                #  生成退费数据
                createRefund(str(getCurrentUser(request)), detailData.detail_id, body, all_state=True)
            else:
                if is_active == 0:
                    old_detail_amount = detailData.amount
                    detailData.amount = old_detail_amount - expense_total
                    totalData = IncomeTotal.objects.get(total_id=detailData.total_id)
                    old_total_amount = totalData.amount
                    totalData.amount = old_total_amount - expense_total
                    detailData.save()
                    totalData.save()
                else:
                    #  删除认证
                    deleteAuth(contractData.account_number)
                    #  收入金额为0
                    updataIncome(contractId)
                    #  合同状态 终止
                    Contract.objects.filter(account_number=contractData.account_number).update(state=3)
                createRefund(str(getCurrentUser(request)), detailData.detail_id, body)
            createHandleLog('用户退费', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《用户退费》权限  操作内容 {body}')
            res['status'] = 200
            res['message'] = '退费成功'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)
